<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="10"><div class="grid-content bg-purple">
        <div class="developer left">
          <div id="box">
            <ul>
              <li v-for="(v, index) in districtList" :key="index">
                <div class="product-content1">
                  <image-preview :src="v.image" alt="Dynamic Image" class="fixed-image-size"/>
                  <div class="info">
                    <h2>{{ v.communityName }}</h2>
                    <h4>小区地址：暂无地址</h4>
                    <h4>辖区：{{ v.name }}</h4>
                  </div>
                  <div class="additional-info1">
                    <p @click="handlePopulationClick(v.id)">实有人口：{{ v.populationNum }}</p>
                    <p @click="handleEstateClick(v.id)">实有房屋：{{ v.realEstateNum }}</p>
                    <p @click="handleUnitClick(v.id)">实有单位：{{ v.unitNum }}</p>
                    <p @click="handleVehiclesClick(v.id)">实有车辆：{{ v.vehicleNum }}</p>
                    <p @click="handleCacheClick(v.id)">实有力量：{{ v.buildingCount }}</p>
                    <p @click="handleFacilitiesClick(v.id)">实有设备：{{ v.securityFacilitiesNum }}</p>
                  </div>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div></el-col>
      <el-col :span="10"><div class="grid-content bg-purple">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="单位名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入单位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="法定代表" prop="populationId">
        <el-select v-model="queryParams.populationId" :clearable="true" placeholder="请选择法定代表人">
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="成立日期" prop="max">
        <el-date-picker clearable
          v-model="queryParams.max"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="开始日期">
        </el-date-picker></el-form-item>至
        <el-form-item prop="min">
        <el-date-picker clearable
                        v-model="queryParams.min"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="单位地址" prop="address">
        <el-input
          v-model="queryParams.address"
          placeholder="请输入单位地址"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <br>
      <el-form-item label="创建时间" prop="max1">
        <el-date-picker clearable
          v-model="queryParams.max1"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="开始时间">
        </el-date-picker>
      </el-form-item>至
        <el-form-item prop="min1">
        <el-date-picker clearable
                        v-model="queryParams.min1"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['community:unit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"

          @click="handleUpdate"
          v-hasPermi="['community:unit:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"

          @click="handleDelete"
          v-hasPermi="['community:unit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['community:unit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <div id="box">
      <ul class="unit-list">
        <li v-for="(v, index) in unitList" :key="index" class="unit-item">
          <div class="product-unit">
            <input type="checkbox" v-model="selectedItems" :value="v.id" class="checkbox-item" @change="handleSelectionChange(v.id)" />
            <image-preview :src="v.image" alt="Dynamic Image" class="fixed-image-size1"/>
            <br>
            <div class="info">
              <h4>单位类别：法人</h4>
              <h4>从业人数 6</h4>
              <h4>单位名称：{{v.name}}</h4>
              <h4>单位地址：{{v.address}}</h4>
              <h4>成立时间：{{v.establishmentDate}}</h4>
              <h4>创建时间：{{v.createDate}}</h4>
              <h4>所在小区：{{ v.communityName }}</h4>
              <h4>联系人：{{ v.populationName }}</h4>
              <h4>电话号码：{{ v.iphone }}</h4>
              <h4>证件号码：{{ v.idCard }}</h4>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
      </div></el-col>
    </el-row>

    <!-- 添加或修改实有单位对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="实有单位照片" prop="image">
          <ImageUpload v-model="form.image" />
        </el-form-item>
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入单位名称" />
        </el-form-item>
        <el-form-item label="法定代表人" prop="populationId">
          <el-select v-model="form.populationId" placeholder="请选择法定代表人">
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成立日期" prop="establishmentDate">
          <el-date-picker clearable
            v-model="form.establishmentDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择成立日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="单位地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入单位地址" />
        </el-form-item>
        <el-form-item label="添加时间" prop="createDate">
          <el-date-picker clearable
            v-model="form.createDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择添加时间">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUnit, getUnit, delUnit, addUnit, updateUnit } from "@/api/community/unit";
import { getDistrictSelect ,listDistrict} from '@/api/community/district'
import { getlistPopulation } from '@/api/community/population'
import ImageUpload from '@/components/ImageUpload'
import { selPopulation } from '@/api/community/population'
export default {
  name: "Unit",
  components: { ImageUpload },
  data() {
    return {
      districtList:[],
      district:[],
      selectedItems:[],
      options:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      //single: true,
      // 非多个禁用
      //multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实有单位表格数据
      unitList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        populationId: null,
        establishmentDate: null,
        address: null,
        createDate: null,
        districtId: null,
        max:null,
        min:null,
        max1:null,
        min1:null
      },
      // 表单参数
      form: {
        districtId:'',
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "单位名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    var id = this.$route.params.id
    if (id != null && id != undefined && id !== '') {
      localStorage.setItem('districtId', id);
    }
    this.getList();
    this.getSelect();
    this.getDistrictList();
    this.getPopulationSelect();
  },
  methods: {
    // 法定代表人下拉框 查询
    getPopulationSelect() {
      this.loading = true;
      var districtId = localStorage.getItem('districtId')
      selPopulation(districtId).then(response => {
        this.options = response.data;
      });
    },
    /** 查询实有单位列表 */
    getList() {
      this.loading = true;
      var item = localStorage.getItem('districtId')
      this.queryParams.districtId = item
      listUnit(this.queryParams).then(response => {
        this.unitList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询实有小区统计列表 */
    getDistrictList() {
      this.loading = true;
      var item = localStorage.getItem('districtId')
      this.queryParams.id = item
      listDistrict(this.queryParams).then(response => {
        this.districtList = response.rows;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        image:null,
        name: null,
        populationId: null,
        establishmentDate: null,
        address: null,
        createDate: null,
        districtId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 小区下拉框查询
    getSelect(){
      getDistrictSelect().then(res=>{
        console.log(res)
        this.district=res.data
      })
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(id) {
      if (this.selectedItems.includes(id)) {
        // 如果选中项中包含当前 id，则从 ids 中添加该 id
        if (!this.ids.includes(id)) {
          this.ids.push(id);
        }
      } else {
        // 如果选中项中不包含当前 id，则从 ids 中移除该 id
        const index = this.ids.indexOf(id);
        if (index !== -1) {
          this.ids.splice(index, 1);
        }
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加实有单位";
    },
    /** 修改按钮操作 */
    handleUpdate() {
      this.reset(); // 重置数据
      // 检查ids数组的长度
      let id = null;
      let name = null;

      if (Array.isArray(this.ids) && this.ids.length === 1) {
        // 如果ids是数组且只有一个元素，使用这个元素作为id
        id = this.ids[0];
        // 假设存在一个数组this.names与ids对应，获取相应的名称
        name = this.names ? this.names[0] : null;
      } else if (Array.isArray(this.ids) && this.ids.length > 1) {
        // 如果ids包含多个元素，给出警告
        this.$message.warning("每次只能修改一个实有单位，请选择单个项目进行修改。");
        return; // 退出方法
      } else if (!Array.isArray(this.ids) || this.ids.length === 0) {
        // 如果ids不是数组或为空，给出警告
        this.$message.warning("请选择一个实有单位项目进行修改。");
        return; // 退出方法
      }
      // 使用获取到的id调用getUnit函数
      getUnit(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改实有单位";
        // 如果存在name，显示信息提示
        if (name) {
          this.$message.info("开始修改操作，单位：" + name);
        }
      });
    },
    /** 提交按钮 */
    submitForm() {
      var item = localStorage.getItem('districtId')
      this.form.districtId = item
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateUnit(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addUnit(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getDistrictList()
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      // 判断是否选中
      if (this.ids.length === 0) {
        this.$modal.msgError("请选择要删除的数据");
        return;
      }
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除实有单位编号为"' + ids + '"的数据项？').then(function() {
        return delUnit(ids);
      }).then(() => {
        this.getDistrictList()
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('community/unit/export', {
        ...this.queryParams
      }, `unit_${new Date().getTime()}.xlsx`)
    },
    // 查询小区 实有人口
    handlePopulationClick(id) {
      this.$router.push({
        path: '/community/population/' + id,
        name: 'Population',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有房屋
    handleEstateClick(id) {
      this.$router.push({
        path: '/community/estate/' + id,
        name: 'Estate',
        params: {
          id: id
        }
      })
    },

    // 查询小区 实有单位
    handleUnitClick(id) {
      this.$router.push({
        path: '/community/unit/' + id,
        name: 'Unit',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有车辆
    handleVehiclesClick(id) {
      this.$router.push({
        path: '/community/vehicles/' + id,
        name: 'Vehicles',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有设备
    handleFacilitiesClick(id) {
      this.$router.push({
        path: '/community/facilities/' + id,
        name: 'Facilities',
        params: {
          id: id
        }
      })
    },
    // 查询小区 实有力量
    handleCacheClick() {
      alert('待开发');
    },
  }
};
</script>
<style scoped>
.product-content1 {
  text-align: center; /* 图片和信息居中对齐 */
  margin-bottom: 20px; /* 底部间距 */
}

.product-content1 .fixed-image-size {
  display: block; /* 确保图片是块级元素 */
  margin: 0 auto 10px auto; /* 图片居中并留下一定的底部间距 */
  max-width: 100%; /* 图片最大宽度为容器宽度 */
  height: 500px; /* 高度自适应，保持比例 */
  width: 500px; /* 固定宽度，可以根据需要调整 */
}

#box {
  display: flex;
  justify-content: center; /* 居中显示 */
}

.unit-list {
  display: flex;
  flex-wrap: wrap;
  padding: 0;
  margin: 0;
  list-style: none;
}
.unit-item {
  width: calc(33.33% - 20px); /* 计算每个项目的宽度，减去外边距 */
  margin: 10px; /* 外边距 */
}

.product-unit {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 10px;
  border: 1px solid #ccc;
  width: 100%; /* 确保每个项目占据父容器的宽度 */
}

.product-unit .fixed-image-size3 {
  display: block; /* 确保图片是块级元素 */
  margin: 0 auto 10px auto; /* 图片居中并留下一定的底部间距 */
  max-width: 100%; /* 图片最大宽度为容器宽度 */
  height: 200px; /* 高度自适应，保持比例 */
  width: 200px; /* 固定宽度，可以根据需要调整 */
}

.info {
  flex: 1; /* 让信息部分占据剩余空间 */
}

.info h4,
.info p {
  margin: 0;
}

.additional-info1 {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 三列布局 */
  grid-gap: 10px; /* 设置网格之间的间距 */
}

.additional-info1 p {
  margin: 0;
}
</style>
